import { useAppStore } from '@/store/modules/app';
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { getStorage } from '@/utils';
import { ElMessage } from 'element-plus';

export const api = import.meta.env.VITE_API;
export const cdn = import.meta.env.VITE_CDN;
export const modelId = import.meta.env.VITE_MODELID;
export const modelType = import.meta.env.VITE_MODELTYPE;
export const model = import.meta.env.VITE_MODEL;

export enum ErrCode {
  success = 0,
  error = 1,
}

// 创建axios实例，减少重复代码
const axiosInstance: AxiosInstance = axios.create({
  baseURL: api,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  },
  validateStatus: () => true,
});

// 请求拦截器添加token
axiosInstance.interceptors.request.use(
  config => {
    const token = getStorage('token');
    if (token && config.headers) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => Promise.reject(error),
);

// 响应拦截器处理统一错误
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 200: 成功, 0: 失败, 401: 未登录
    if (response.status === 401) {
      const appStore = useAppStore();
      ElMessage.closeAll();
      ElMessage.error('未登录或登录已过期，请重新登录');
      appStore.logOut();
      return Promise.reject(response);
    }
    if (response.status !== 200) {
      ElMessage.error(response.data?.msg || '请求失败，请稍后重试');
      return Promise.reject(response);
    }
    // 兼容后端返回的 code 字段
    if (response.data && response.data.code === 0) {
      ElMessage.error(response.data?.msg || '请求失败，请稍后重试');
      return Promise.reject(response.data);
    }
    return response;
  },
  error => {
    ElMessage.error('请求失败，请稍后重试');
    return Promise.reject(error);
  },
);

// 封装请求方法
const request = async <T>(url: string, method: string, options: AxiosRequestConfig): Promise<T> => {
  const { data, status } = await axiosInstance({
    method,
    url,
    ...options,
  });
  return data;
};

// 封装 GET 请求
export const get = <T>(url: string, params?: Record<string, any>): Promise<T> => request<T>(url, 'get', { params });

// 封装 POST 请求
export const post = <T>(
  url: string,
  data?: Record<string, any>,
  responseType?: AxiosRequestConfig['responseType'],
): Promise<T> =>
  request<T>(url, 'post', {
    data: JSON.stringify(data),
    responseType,
  });

// 上传表单数据
export const postFormData = <T>(url: string, data?: Record<string, any>, params?: any): Promise<T> => {
  return request<T>(url, 'post', {
    data,
    params,
    headers: {
      'Content-Type': 'multipart/form-data',
      teamId: getStorage('teamId') || '',
    },
  });
};

// 上传二进制数据
export const postBuffer = <T>(url: string, data?: Record<string, any>): Promise<T> => {
  return request<T>(url, 'post', {
    data,
    headers: {
      'Content-Type': 'application/octet-stream',
    },
  });
};

// PUT 请求
export const put = <T>(url: string, data?: Record<string, any>): Promise<T> =>
  request<T>(url, 'put', {
    data: JSON.stringify(data),
  });

// DELETE 请求
export const del = <T>(url: string, params?: Record<string, any>): Promise<T> =>
  request<T>(url, 'delete', {
    params,
  });
